<template>
  <div class="w-[98%] p-20px">
    <div style="margin-bottom: 10px">
      <el-select style="width: 130px" v-model="filter.indexId" placeholder="合作编号" clearable
                 filterable>
        <el-option v-for="item in agencyList" :key="item.id" :label="item.agencyName"
                   :value="item.indexId"></el-option>
      </el-select>


      <el-select style="width: 100px;margin-left: 10px" v-model="filter.sex" placeholder="性别"
                 clearable>
        <el-option label="男" value="男"></el-option>
        <el-option label="女" value="女"></el-option>
      </el-select>

      <el-select style="width: 130px;margin-left: 10px" v-model="filter.businessType" placeholder="业务类型"
                 clearable>
        <el-option v-for="item in getEnumBySn('businessType').filter(item=>item.label.startsWith('托管'))" :label="item.label"
                   :key="item.value"
                   :value="item.value"></el-option>
      </el-select>

      <el-select v-model="filter.trusteeshipType" required style="width: 130px;margin-left: 10px"
                 clearable
                 placeholder="托管类型">
        <el-option v-for="item in getEnumBySn('cycleTypeEnum')" :label="item.label"
                   :key="item.value"
                   :value="item.value"></el-option>
      </el-select>
      <el-date-picker type="date" v-model="filter.startTime" value-format="YYYY-MM-DD"
                      placeholder="开始时间"/>
      <el-date-picker style="margin-left: 20px" type="date" v-model="filter.endTime"
                      value-format="YYYY-MM-DD"
                      placeholder="结束时间"/>
      <el-input v-model="filter.transferPhone" clearable filterable placeholder="转移手机号"
                 style="width: 200px;">
      </el-input>
      <el-input style="width: 100px" v-model="filter.nativePlace" clearable filterable placeholder="籍贯"></el-input>
      <el-input style="width: 150px;" v-model="filter.customName"
                placeholder="客户姓名"
                clearable></el-input>
      <el-input style="width: 150px;" placeholder="平台" v-model="filter.hasPlatformName"></el-input>
      <el-button type="primary" :loading="loading" @click="debouncedFetchData" style="margin-left: 10px">查询</el-button>
    </div>


    <el-table :data="tableData" style="width: 100%" border stripe show-overflow-tooltip v-loading="loading">
      <el-table-column label="序号" width="60" align="center">
        <template #default="{ $index }">
          {{ $index + 1 }} <!-- 使用 $index 计算序号 -->
        </template>
      </el-table-column>
      <el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop"
                       :label="column.label"
                       :width="column.width" :align="column.align"></el-table-column>
      <el-table-column label="操作" width="360px" align="center">
        <template v-slot="scope">
          <el-button @click="editHandle(scope.row)" size="mini" :type="getEditButtonType(scope.row)">身份信息</el-button>
          <el-button @click="openDrawer('edit', scope.row)" size="mini" :type="getRecordButtonType(scope.row)">
            欠款平台明细
          </el-button>
          <el-button @click="openVisible(scope.row.orderId)" size="mini" type="danger">接听记录
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" width="140px" prop="identityPhone" align="center"/>
    </el-table>

    <el-pagination :current-page="currentPage" :page-size="pageSize" :total="totalItems"
                   @current-change="currentChange"
                   background layout="total,prev, pager, next" class="pagination" prev-text="上一页"
                   next-text="下一页"></el-pagination>

    <employeeList v-if="drawerVisible" :currentItem="currentItem" :EnumA="EnumA" :EnumB="EnumB"
                  @close="closeDrawer"
                  @save="saveItem"/>
    <el-drawer v-model="Visible" size="60%" :before-close="closeVisible">
      <Custody v-if="Visible" :orderId="currentOrderId" :filter="filter" @close="closeVisible"/>
    </el-drawer>
    <Modal ref="modalRef" @ok="okHandle"/>
  </div>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue';
import employeeList from './employeeList.vue'; // 引入子组件
import Custody from '../Custody/index.vue'; // 引入子组件
import Modal from "./modal.vue"
import {getEnumBySn} from "@/api/enums";
import request from '@/config/axios'
import { debounce } from 'lodash-es'

const filter = ref({
  gender: '',
  trusteeshipType: ""
});
const Visible = ref(false);
const modalRef = ref();

// 使用防抖包装fetchData函数，设置0.5秒的防抖时间
const debouncedFetchData = debounce(async () => {
  loading.value = true;
  try {
    const response = await request.get({
      url: '/order/listOrderInfoForTrusteeship',
      params: {...filter.value, current: currentPage.value, size: pageSize.value}
    })
    tableData.value = response.records
    totalItems.value = response.total
    currentPage.value = response.current
  } finally {
    loading.value = false;
  }
}, 500); // 0.5秒的防抖时间

// 监听除了平台之外的所有筛选项
watch(
  () => ({
    indexId: filter.value.indexId,
    sex: filter.value.sex,
    businessType: filter.value.businessType,
    trusteeshipType: filter.value.trusteeshipType,
    startTime: filter.value.startTime,
    endTime: filter.value.endTime,
    transferPhone: filter.value.transferPhone,
    nativePlace: filter.value.nativePlace,
    customName: filter.value.customName
  }),
  () => {
    debouncedFetchData();
  },
  { deep: true }
);

const tableData = ref([]);
const EnumA = ref([]);
const EnumB = ref([]);
const agencyList = ref([])
const loading = ref(false); // 添加loading状态变量

const columns = ref([
  {prop: 'orderStatus', label: '状态', width: '70', align: 'center'},
  {prop: 'businessType', label: '业务类型', width: '100', align: 'center'},
  {prop: 'orderReceiveDate', label: '接单日期', width: '180', align: 'center'},
  {prop: 'orderEndDate', label: '结束日期', width: '180', align: 'center'},
  {prop: 'indexId', label: '合作编号', width: '90', align: 'center'},
  {prop: 'customName', label: '客户姓名', width: '100', align: 'center'},
  {prop: 'phoneCode', label: '转接手机号', width: '180',},
  {prop: 'trusteeshipType', label: '托管类型', width: '90', align: 'center'},
  {prop: 'nativePlace', label: '籍贯', width: '90', align: 'center'},
  {prop: 'trusteeshipMemo', label: '客户主观意愿', align: 'center', width: '200',}

]);

const totalItems = ref(0);
const currentPage = ref(1);
const pageSize = ref(15);
const drawerVisible = ref(false);
const currentItem = ref({});
const actionType = ref('');

const currentChange = (v) => {
  currentPage.value = v
  debouncedFetchData()
}

const okHandle = () => {
  debouncedFetchData()
}

function openDrawer(action, item = {}) {
  actionType.value = action;
  currentItem.value = {...item};
  drawerVisible.value = true;
  currentOrderId.value = item.orderId
}

function closeDrawer() {
  drawerVisible.value = false;
  // debouncedFetchData(); //获取列表
}

const currentOrderId = ref('');

function openVisible(orderId) {
  Visible.value = true
  currentOrderId.value = orderId
}

function closeVisible() {
  Visible.value = false
}

function saveItem(item) {
  if (actionType.value === 'add') {
    item.id = totalItems.value + 1;
    tableData.value.push(item);

  } else if (actionType.value === 'edit') {
    const index = tableData.value.findIndex(i => i.id === item.id);
    tableData.value.splice(index, 1, item);
  }
  totalItems.value = tableData.value.length;
  closeDrawer();
}


const editHandle = (rowData) => {
  modalRef.value?.edit(rowData)
}

const transferPhoneList = ref([]);

const fetchEnumList = async () => {
  EnumA.value = [
    {id: 1, name: '招商银行信用卡',},
    {id: 2, name: '分期乐',},
    {id: 3, name: '花呗',},
    {id: 4, name: '借呗',},
    // 重复项可去除
  ];
  EnumB.value = [
    {phone: 18512202434, name: '尹思盈',},
    {phone: 15455442223, name: '赵春楠',},
    {phone: 18512345545, name: '刘宝意',},
    {phone: 12442223444, name: '宝坻手机号',},
    // 重复项可去除
  ];

  agencyList.value = await request.get({
    url: '/agency/list',
    data: {}
  })

  transferPhoneList.value = await request.get({
    url: '/transferPhone/list',
    params: {}
  })


};

const getEditButtonType = function (row) {
  if (row.nativePlace && row.identityCard && row.identityAddress && row.identityPhone && row.transferType) {
    return 'success'
  }else{
    return 'warning'
  }
}

const getRecordButtonType = function (row) {
  if (row.hasDetailFlag == '1') {
    return 'success'
  } else {
    return 'warning'
  }
}

onMounted(() => {
  debouncedFetchData(); //获取列表
  fetchEnumList() // 获取下拉列表
});
</script>

<style scoped>
.filter-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.filter-section > * {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  float: right;
  font-size: 22px;
}

.drawer-footer {
  text-align: right;
  margin-top: 20px;
}

.form-inline {
  display: flex;
  flex-wrap: wrap;
}

.form-inline .el-form-item {
  margin-right: 20px;
}
</style>
